package com.company.finance.ddd.domain.core.voucher.event.handler;

import com.company.finance.ddd.domain.core.voucher.VoucherService;
import com.company.finance.ddd.domain.core.voucher.event.VoucherCreateFailedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Observable;

/**
 *
 * @author wanglei
 * @version $$Id: MailSender, v 0.1 2021/2/2 17:48 wanglei Exp $$
 */
@Component
@Slf4j
public class VoucherCreateFailedEventHandler implements EventHandler {

    @Autowired
    private VoucherService voucherService;

    public VoucherCreateFailedEventHandler(Observable publisher) {
    }

    @Override
    public void update(Observable publisher, Object event) {
        if (!(event instanceof VoucherCreateFailedEvent)) {
            return;
        }
        log.info("Event -> {}", event);

        VoucherCreateFailedEvent failedEvent = (VoucherCreateFailedEvent) event;

        StringBuilder ids = new StringBuilder();
        voucherService.query(VoucherService.VoucherQueryParam.builder()
                .billId(failedEvent.getBillId()).build())
                .forEach(voucher -> {
                    ids.append("voucherId -> ").append(voucher.getID()).append("billId -> ")
                            .append(failedEvent.getBillId());
                });
        log.info("Send mail to some employees, thereby make them to notice that the reason of failure. {}", ids);

    }
}
